#!/usr/bin/python
import os
import re
import sys

if len(sys.argv)<2: raise Exception('Require one argument.')
if os.path.exists(sys.argv[1]): raise Exception('%s exists.'%sys.argv[1])
out=open(sys.argv[1],'w')

# download files according to 'WhereAreThey'
# if file exists in /srcpkg/, then do not download
# downloaded files are saved to /srcpkg/
# print a list 'file_path'

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0]))) # chdir to the directory where `unpack' stays
f=open('WhereAreThey','r')
for line in f:
	line = line.strip()
	if len(line)==0:
		continue
	elif line[0]=='#': # is a comment
		continue
	elif line.find('http://')==0:
		filename=re.search('[^/]+$',line)
		if filename==None: raise Exception('File `WhereAreThey` format error.')
		filename=filename.group(0)
		path='/srcpkg/'+filename
		if os.path.exists(path)==False:
			cmd='wget -c --tries=20 %s'%line # continue getting, 20 tries, turn off verbose without being completely quiet
			if os.system(cmd): 
				raise Exception('Cannot download %s'%filename, cmd)
			if os.system('mv %s /srcpkg/'%filename):
				raise Exception('Cannot move %s into /srcpkg/'%filename)
		out.write(path+'\n') # output filepath
